-module(toplevel_block).
-include_lib("nitrogen/include/wf.inc").
-compile(export_all).

						%Builders
assemble_header(X) ->
    X.

assemble_menu(X) ->
    X ++ assemble_body([]).

assemble_body(X) ->
    X ++ [
	  #p{},
	  #textbox{id=tb_code, class="tb_code"},
	  #button{text="Evaluer", actions=helper:act(?MODULE, {eval_code, body})},

	  #p{},
	  #table { class="tb_table", 
		   rows=[
			 #tablerow { cells=[
					    #tableheader { class="tb_table_from" },
					    #tableheader { class="tb_table_output" }
					   ]},
			 #tablerow { cells=[
					    #tablecell { id=tb_from },
					    #tablecell { id=tb_output }
					   ]}
			]}
	 ].
						%Wiring

wire() ->
    ok.
						%Behavior
behave(_) ->
    ok.
						%Events
event({eval_code, body}) ->
    [Code] = wf:q(tb_code),

    hertz_top ! {talk, helper:id_me(), self(), {Code}},
    {From, Output} = receive
			 {ok, Out} ->{"> ", Out};
			 error -> {"XX", "Une erreur est survenue, rafraichissez la page"}
		     end,
    Module = hglobals:vget(helper:id_me(), caller),

    %To factorise... this is ugly
    Module:exec( fun(X) ->
			 wf:insert_bottom(tb_from, 
					  #panel{ body=X}) end, "# " ),
    Module:exec( fun(X) ->
			 wf:insert_bottom(tb_output,
					  #panel{ body=X, class="tb_icode"}) end, Code), 
    Module:exec( fun(X) ->
			 wf:insert_bottom(tb_from, 
					  #panel{ body=X}) end, From ),
    Module:exec( fun(X) ->
			 wf:insert_bottom(tb_output,
					  #panel{ body=X}) end, Output ),
    ok;			
event(_) ->
    ok.
